/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ceair.flight.refund.service.cronjob.autocheck.impl;

import com.ceair.flight.refund.dto.appmoblie.RefundApplyDto;
import com.ceair.flight.refund.dto.appmoblie.RefundTktDto;
import com.ceair.flight.refund.location.model.FlightOrderDO;
import com.ceair.flight.refund.location.model.PaxDO;
import com.ceair.flight.refund.location.model.TicketDO;
import com.ceair.flight.refund.location.service.IRefundLocationService;
import com.ceair.flight.refund.service.cronjob.autocheck.ITicketIssuedIn24HChecker;
import com.ceair.flight.refund.service.external.IOrderOperation;
import com.ceair.muservice.basicdata.dto.channel.ChannelManageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

/**
 *
 * @author Colin_You
 */
@Service
public class TicketIssuedIn24HCheckerImpl implements ITicketIssuedIn24HChecker {

    private static final Logger LOG = LoggerFactory.getLogger(TicketIssuedIn24HCheckerImpl.class);

    @Resource(name = "cacheOrderOperationImpl")
    private IOrderOperation orderOpt;
    @Autowired
    private IRefundLocationService refundLocationService;
    private static final String SOUTH_KOREA = "KR";

    @Override
    public boolean checkIssuedIn24H(RefundApplyDto refundApply) {
        Date issueDate = getTicketIssuedDate(refundApply);
        return (!isKorean(refundApply) && checkIssuedIn24H(issueDate)) || (isKorean(refundApply) && isInKoreaDay(issueDate.getTime()));
    }

    private Date getTicketIssuedDate(RefundApplyDto refundApply) {
        RefundTktDto refundTkt = refundApply.getRefundTkt();
        String flightOrderNo = refundTkt.getFlightOrderNo();
        String ticketNo = refundTkt.getTicketNo();
        return getTicketIssuedDate(flightOrderNo, ticketNo);
    }

    private Date getTicketIssuedDate(String flightOrderNo, String ticketNo) {
        LOG.info("Getting ticket No {} issued date", ticketNo);
        FlightOrderDO flightOrder = orderOpt.getFlightOrderDetail(flightOrderNo);
        Set<PaxDO> paxs = flightOrder.getPaxs();
        Date issueDate = null;
        for (PaxDO pax : paxs) {
            String paxTicketNo = pax.getTktNo();
            if (!paxTicketNo.contains(ticketNo)) {
                continue;
            }
            Set<TicketDO> tickets = pax.getTickets();
            for (TicketDO ticketDO : tickets) {
                String paxTkt = ticketDO.getTktNo();
                Date date = ticketDO.getTktDate();
                if (ticketNo.contains(paxTkt)) {
                    if (issueDate == null || issueDate.before(date)) {
                        issueDate = date;
                    }
                }
            }
        }
        LOG.info("Getting ticket No {} issued date is {}", ticketNo, issueDate);
        return issueDate;
    }

    private boolean checkIssuedIn24H(Date issueDate) {
        if (issueDate == null) {
            LOG.error("Ticket issue date is empty");
            return false;
        }
        Date tktIssueDate = new Date(issueDate.getTime());
        LOG.info("Ticket issue date is {}", tktIssueDate);
        Calendar calendar = Calendar.getInstance();
        Calendar issuedCalendar = Calendar.getInstance();
        issuedCalendar.setTime(tktIssueDate);
        issuedCalendar.add(Calendar.HOUR_OF_DAY, 24);
        boolean isIn24H = calendar.before(issuedCalendar);
        LOG.info("Ticket issue date is {}in 24 hours", isIn24H ? " " : "NOT ");
        return isIn24H;
    }

    private boolean isKorean(RefundApplyDto refundApply) {
        RefundTktDto refundTkt = refundApply.getRefundTkt();
        String orderChannelNo = refundTkt.getChannelNo();
        return isKorean(orderChannelNo);
    }

    private boolean isKorean(String orderChannelNo) {
        ChannelManageDto channelManageDto = refundLocationService.findChannelByCode(orderChannelNo);
        if (channelManageDto != null) {
            String country = channelManageDto.getNationCode();
            return country != null && country.endsWith(SOUTH_KOREA);
        }
        LOG.error("Channel {} not found", orderChannelNo);
        return false;
    }

    /**
     * 判断给定的日期时间是否是在韩国的当天里
     *
     * @param ticketIssueTime
     * @return
     */
    private boolean isInKoreaDay(long ticketIssueTime) {
        long sysTime = new Date().getTime();
        long hour = 60 * 60 * 1000;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        long koreanIssueTime = ticketIssueTime + hour;//加一个小时
        long koreanTime = sysTime + hour;//韩国当天时间
        Date koreanDate = new Date(koreanTime);
        String dayBegin = df.format(koreanDate);//韩国当天日期
        try {
            long koreanBeginTime = df.parse(dayBegin).getTime();//韩国当天开始时间
            long koreanEndTime = koreanBeginTime + 24 * hour;//韩国当天结束时间
            if (koreanIssueTime >= koreanBeginTime && koreanIssueTime < koreanEndTime) {//给定时间大于开始时间且小于结束时间
                return true;
            }
        } catch (ParseException ex) {
            //ignore
        }
        return false;
    }

}
